package com.manong.util;

import org.apache.commons.codec.binary.Base64;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.UUID;

public class VerifyCodeUtil {
    public static final int WIDTH = 100;
    public static final int HEIGHT = 50;
    public static final String CHARS = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    public static final int CODE_LENGTH = 4;
    public static final int BG_COLOR = 0xDCDCDC;

    public static Map<String, String> generateVerifyCode() {
        Map<String, String> map = new HashMap<>();
        // 创建内存图像并获取图形上下文
        BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();

        // 产生随机验证码
        char[] rands = new char[CODE_LENGTH];
        for (int i = 0; i < CODE_LENGTH; i++) {
            int rand = new Random().nextInt(CHARS.length());
            rands[i] = CHARS.charAt(rand);
        }
        map.put("code", new String(rands));

        // 画背景
        g.setColor(new Color(BG_COLOR));
        g.fillRect(0, 0, WIDTH, HEIGHT);

        // 随机生产120个干扰点
        int len = 120;
        for (int i = 0; i < len; i++) {
            int x = (int) (Math.random() * WIDTH);
            int y = (int) (Math.random() * HEIGHT);
            int red = new Random().nextInt(255);
            int green = new Random().nextInt(255);
            int blue = new Random().nextInt(255);
            g.setColor(new Color(red, green, blue));
            g.drawRect(x, y, 1, 0);
        }

        // 设置验证码字符的颜色和字体
        g.setColor(Color.BLACK);
        g.setFont(new Font("Times New Roman", Font.PLAIN, 18));

        // 在不同位置输出验证码的不同字符
        int x = 10; // 初始 x 坐标
        for (int i = 0; i < CODE_LENGTH; i++) {
            g.drawString(String.valueOf(rands[i]), x, 30);
            x += 20; // 每个字符的 x 坐标递增
        }

        g.dispose();

        // 将图像传到客户端
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "JPEG", baos);
            byte[] buffer = baos.toByteArray();
            String uuid = UUID.randomUUID().toString();
            map.put("uuid", uuid);
            map.put("img", Base64.encodeBase64String(buffer));
        } catch (IOException e) {
            e.printStackTrace();
        }

        return map;
    }

    public static Boolean verification(String code, String verifyCode, boolean ignoreCase) {
        if (code != null && verifyCode != null) {
            return ignoreCase ? verifyCode.equalsIgnoreCase(code) : verifyCode.equals(code);
        }
        return false;
    }
}
